// created by bjh 2017-10-12
// 职工列表筛选功能
import React from "react";
import PropTypes from "prop-types";
import { List, Badge } from "@ali/ding-ui";

const Item = List.Item;


// components
import Avatar from "../../components/Avatar";
import Icon from "../../components/Icon";

//utils
import { setRight, close, setTitle, complexPicker, alert, setLeft  } from "../../utils/dingtalk.js";
import { get } from "../../utils/db.js";

// 当前员工的状态和类型固定 
const employeeStatus = [
    // { id: "1", text: "待入职" },
    { id: "3", text: "正式" },
    { id: "2", text: "试用期" },
    // { id: "4", text: "离职" },
    { id: "5", text: "待离职" },
]
const employeeType = [
    { id: "1", text: "全职" },
    { id: "2", text: "兼职" },
    { id: "3", text: "实习" },
    { id: "4", text: "劳务派遣" },
    { id: "5", text: "退休返聘" },
    { id: "6", text: "劳务外包" },
]
const MAX_DEPARTMENTS = 100;

class Filter extends React.Component {
    constructor(props, context) {
        super();
        this.state = {
            showBlock: false,
            deptsId: [],
            deptsName: [],
            typeChoosed: employeeType.filter((item) => { item.choosed = false; return true }),
            statuesChoosed: employeeStatus.filter((item) => { item.choosed = false; return true }),
        };
        //记录组件被选中部门以及对应的人数
        this.data = {};
    }

    bindListener = () => {
        document.querySelector('#filterTab').addEventListener('touchmove', function (e) {
            e.preventDefault();
        });
    }
    /*
    *   调用dingtalk内部api来选择部门 
    *   这里获取被选中的部门
    */
    chooseDepartment = (e) => {
        e.preventDefault();
        // const corpId = getUrlParam("corpId");
        const corpId = get("corpId");
        const { deptsId } = this.state;
        complexPicker({
            title: "选择部门",
            multiple: true, // 多选
            pickedDepartments: deptsId || [], // 已选部门
            maxDepartments: MAX_DEPARTMENTS, // 最大部门数
            corpId,
            isNeedSearch: true,
            local: "true",
            cb: result => {
                console.log(result);
                let dept = [];
                let { departments } = result;
                departments.sort((a, b) => a.id - b.id);
                departments.forEach(val => {
                    dept.push({ deptId: val.id, deptName: val.name });
                });
                const deptsId = departments.map(val => val.id);
                this.setState({
                    deptsId,
                    deptsName: departments.map(val => val.name),
                    deptMapList: dept,
                });
                this.props.onFilter && 
                this.props.onFilter(
                    this.formatterDeptData(result), 
                    { depts: this.formatterDeptText(result) },
                );
            },
            errCb: err => alert({ title: "出错了", message: JSON.stringify(err) })
        });
    }

    // 格式化选中部门数据 用于接口
    formatterDeptData = (data) => {
        let result = {
            depts: [],
            userIds: [],
        };
        this.data = Object.assign({}, data);
        data.departments.map((item) => {
            result.depts.push(item.id);
        });
        data.users.map((item)=>{
            result.userIds.push(item.emplId);
        })
        result.depts = result.depts.join(",");
        result.userIds = result.userIds.join(",");
        return result;
    }

    // 格式化选中部门数据 用于tab显示
    formatterDeptText = (data) => {
        let result = [];
        data.departments.map((item)=>{
            result.push(item.name);
        });
        return result;
    }

    chooseCategory = (e) => {
        e.preventDefault();
        this.setShowBlock(true);
    }

    setShowBlock = (bool = false) => {
        this.setState({
            showBlock: bool,
        }, () => {
            //绑定滚动事件
            this.bindListener()
            //左上角返回按钮注入新的回调事件
            setLeft({
                onClick: () =>
                    this.setState(
                        {
                            showBlock: false
                        },
                        setLeft({})
                    )
                });
        });
    }

    getValue() {
        var typeChoosed = this.state.typeChoosed.filter((item) => { return item.choosed })
        var statuesChoosed = this.state.statuesChoosed.filter((item) => { return item.choosed })
        return {
            employee: [
                ...typeChoosed,
                ...statuesChoosed,
            ],
            dept: this.data.departments || [],
        }
    }

    //选择员工类型和状态
    toggleChoose = (item) => {
        var func = (newItem, index) => {
            if (newItem.id === item.id && newItem.text === item.text) {
                newItem.choosed = !newItem.choosed;
                return newItem
            }
            return newItem
        }
        this.setState({
            typeChoosed: this.state.typeChoosed.slice(0).map(func),
            statuesChoosed: this.state.statuesChoosed.slice(0).map(func)
        })
    }

    //重置按钮
    reset = () => {
        var func = (item, index) => {
            item.choosed = false;
            return item
        }
        this.setState({
            typeChoosed: this.state.typeChoosed.slice(0).map(func),
            statuesChoosed: this.state.statuesChoosed.slice(0).map(func)
        })
    }

    //确认员工状态和类型
    confirm = () => {
        let result = {
            employTypes: [],
            employStatus: [],
        };
        let textArray = [];
        this.state.typeChoosed.map((item, index) => {
            if (item.choosed == true) {
                result.employTypes.push(item.id);
                textArray.push(item.text);
            }
        });
        this.state.statuesChoosed.map((item, index) => {
            if (item.choosed == true) {
                result.employStatus.push(item.id);
                textArray.push(item.text);
            }
        });
        result.employTypes = result.employTypes.join(",");
        result.employStatus = result.employStatus.join(",");
        this.props.onFilter && 
        this.props.onFilter(result, {
            employee: textArray
        });
        this.setState({
            showBlock: false,
        }, setLeft({}));
    }

    render() {
        return (
            <div className="on-job-filter">
                <div className="on-job-filter-box" onClick={(e) => { 
                    window._rlog("_joblist_dept")
                    this.chooseDepartment(e) }}>
                    <img 
                        className="on-job-filter-box-icon" 
                        src="https://gw.alicdn.com/tfs/TB1BiyTl3oQMeJjy0FpXXcTxpXa-960-876.svg"/>
                    部门筛选
                </div>
                <div className="on-job-filter-box" onClick={(e) => { 
                    window._rlog("_joblist_type")
                    this.chooseCategory(e) }}>
                    <img 
                        className="on-job-filter-box-icon" 
                        src="https://gw.alicdn.com/tfs/TB1P.ujhfxNTKJjy0FjXXX6yVXa-854-854.svg"/>
                    类型筛选
                </div>
                {
                    this.state.showBlock ? this.renderTab() : null
                }
            </div>
        )
    }

    renderTab() {
        return (
            <div className="on-job-filter-tab" id="filterTab" >
                <div className="on-job-filter-tab-title">
                    <Badge text="" dot style={{ marginLeft: 12, background: "#17C295" }} />员工状态
                </div>
                <div className="on-job-filter-tab-view">
                    {employeeStatus.slice(0, 3).map((item, index) => {
                        return this.renderButton(item, "on-job-filter-tab-button-active-one")
                    })}
                </div>
                <div className="on-job-filter-tab-title">
                    <Badge text="" dot style={{ marginLeft: 12, background: "#4DA9EB" }} />员工类型
                </div>
                <div className="on-job-filter-tab-view">
                    {employeeType.slice(0, 3).map((item, index) => {
                        return this.renderButton(item, "on-job-filter-tab-button-active-two")
                    })}
                </div>
                <div className="on-job-filter-tab-view">
                    {employeeType.slice(3).map((item, index) => {
                        return this.renderButton(item, "on-job-filter-tab-button-active-two")
                    })}
                </div>
                <div className="on-job-filter-tab-buttons">
                    <div className="on-job-filter-tab-reset" onClick={this.reset}>重置</div>
                    <div className="on-job-filter-tab-confirm" onClick={this.confirm}>确定</div>
                </div>
            </div>
        )
    }

    renderButton(item, activeClass) {
        return (
            <div
                key={item.id}
                className={`on-job-filter-tab-button ${item.choosed ? activeClass : ""}`}
                onClick={() => this.toggleChoose(item)}>
                {item.text}
            </div>
        )
    }

}

export default Filter